import java.util.*;

/**
 * @author LKQ
 * @date 2022/6/14 9:19
 * @description
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        solution.findDiagonalOrder(mat);
    }
    public int[] findDiagonalOrder(int[][] mat) {
        int m = mat.length, n = mat[0].length;
        int[] ans = new int[m * n];
        int idx = 0;
        // 对角线编号，偶数是从下到上遍历，奇数是从上到下遍历
        for (int i = 0; i < m + n - 1; i++) {
            if (i % 2 == 1) {
                int x = i < n ? 0 : i - n + 1;
                int y = i < n ? i : n - 1;
                while (x < m && y >= 0) {
                    ans[idx++] = mat[x][y];
                    x++;
                    y--;
                }
            } else {
                int x = i < m ? i : m - 1;
                int y = i < m ? 0 : i - m + 1;
                while (x >= 0 && y < n) {
                    ans[idx++] = mat[x][y];
                    x--;
                    y++;
                }
            }
        }
        return ans;
    }
}
